<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('菜单名称')" prop="menu.id">
            <treeselect v-model="form.menu.id" :options="menuOptions" :default-expand-level="99" :show-count="true" :placeholder="$t('请选择')" @open="handleOpen">
              <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
              <label slot="value-label" slot-scope="{ node }">
                {{ $t(node.label) }}
              </label>
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('流程名称')" prop="procDefKeyList">
            <el-select v-model="form.procDefKeyList" multiple :placeholder="$t('请选择')" filterable @change="getFormInfo(form.procDefKey)">
              <el-option
                v-for="process in procDefKeyOptions"
                :key="process.key"
                :label="$t(process.name)"
                :value="process.key"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否发布至流程工作台')" prop="whetherReleaseWorkbench">
            <el-radio-group v-model="form.whetherReleaseWorkbench">
              <el-radio
                v-for="(dict, index) in sysYesOrNoOptions"
                :key="index"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.whetherReleaseWorkbench === 'Y'" :span="12">
          <el-form-item :label="$t('功能类型')" prop="functionType">
            <dict-select
              v-model="form.functionType"
              dictionary="flow_type"
              :placeholder="$t('功能类型')"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">
          <el-form-item :label="$t('部门名称')" prop="deptId">
            <DeptSelect v-model="form.deptId" :placeholder="$t('部门名称')" />
          </el-form-item>
        </el-col>-->
        <el-col v-if="form.whetherReleaseWorkbench === 'Y' || isForm" :span="12">
          <el-form-item prop="formType">
            <span slot="label">
              {{ $t('表单类型') }}
              <!--              <el-tooltip :content="$t('仅自由流情况可选择,其他情况默认为流程绑定的表单')" placement="top">-->
              <!--                <i class="el-icon-question" />-->
              <!--              </el-tooltip>-->
            </span>
            <el-select v-model="form.formType" :placeholder="$t('请选择')" filterable @change="getFormList(form.formType)">
              <el-option
                v-for="dict in formTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.whetherReleaseWorkbench === 'Y' || isForm" :span="12">
          <el-form-item prop="formId">
            <span slot="label">
              {{ $t('使用表单') }}
              <!--              <el-tooltip :content="$t('仅自由流情况可选择,其他情况默认为流程绑定的表单')" placement="top">-->
              <!--                <i class="el-icon-question" />-->
              <!--              </el-tooltip>-->
            </span>
            <el-select v-model="form.formId" filterable :placeholder="$t('请选择')">
              <el-option
                v-for="formOption in formList"
                :key="formOption.id"
                :label="formOption.name"
                :value="formOption.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.whetherReleaseWorkbench === 'Y'" :span="12">
          <el-form-item :label="$t('排序')" prop="sort">
            <el-input v-model="form.sort" :placeholder="$t('排序')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col v-if="form.whetherReleaseWorkbench === 'Y'" :span="12">
          <el-form-item :label="$t('流程logo')" prop="logoInfo">
            <UploadAvatar :logo-info="form.logoInfo" @appendData="uploadImg($event)" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <SaveBtn has-permi="act:process" />
    </div>
  </div>
</template>

<script>
import { saveWfMenuProcess, getWfMenuProcess, checkMenuKey, uploadAvatar } from '@/api/act/process/wfMenuProcess'
    import { listDataProcess } from '@/api/act/process/actProcess'
    import { getFormInfo } from '@/api/act/model/actModel'
    import { getFormList } from '@/api/act/config/wfApplyForm'
    // 菜单
    import { treeselect } from '@/api/system/menu'
    import Treeselect from '@riophae/vue-treeselect'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import UploadAvatar from '@/components/Avatar/uploadAvatar.vue'

    export default {
      components: {
        UploadAvatar,
        Treeselect
      },
      data() {
        return {
          // 表单参数
          form: {
            id: undefined,
            procDefKey: undefined,
            formType: undefined,
            fromValue: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            menu: {
              id: undefined
            },
            deptId: undefined,
            procDefKeyList: []
          },
          // 遮罩层
          loading: false,
          // 表单属性是否可以修改(只有自由流的时候可以改)
          formInfoDisabled: true,
          // 表单类型字典
          formTypeOptions: [],
          // 系统是否
          sysYesOrNoOptions: [],
          // 绑定表单集合
          formList: [],
          // 表单校验
          rules: {
            'menu.id': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }, { validator: this.checkMenuKey, trigger: 'change' }],
            procDefKey: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            procDefKeyList: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            logoInfo: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            functionType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            whetherReleaseWorkbench: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            sort: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          },
          // 菜单树选项
          menuOptions: [],
          // 流程下拉框
          procDefKeyOptions: [],
          // 隐藏表单类型和使用表单
          isForm: false
        }
        },
        watch: {
             wfMenuProcessData: function() {
               this.form = this.wfMenuProcessData
            }
        },
        created() {
          listDataProcess().then(response => {
            this.procDefKeyOptions = response.data
          })
          this.getDicts('sys_yes_no').then(response => {
            this.sysYesOrNoOptions = response.data
          })
          this.getDicts('form_type').then(response => {
            this.formTypeOptions = response.data
          })
        }, mounted() {
          this.getTreeselect()
        },

        methods: {
            handleOpen() {
              this.$nextTick(() => {
                var dom = document.getElementsByClassName('vue-treeselect__menu')[0]
                if (!this.form.menu.id) {
                  if (dom !== null) {
                    dom.scrollTop = 0
                  }
                } else {
                  var domSelect = document.getElementsByClassName('vue-treeselect__option--selected')[0]
                  if (dom !== null) {
                    dom.scrollTop = domSelect.offsetTop
                  }
                }
              })
            },
            // 初始化数据
            init(id) {
              this.loading = true
              if (id != null && id !== '') {
                getWfMenuProcess(id).then(response => {
                  this.form = response.data
                  if (this.isForm) {
                    this.getFormInfo(this.form.procDefKey)
                  }
                  this.getFormList(this.form.formType)
                  this.loading = false
                })
              } else {
                this.reset()
                this.loading = false
              }
            },
            // 上传图片
            uploadImg(data) {
              const formData = new FormData()
              formData.append('avatarfile', data)
              formData.append('id', this.form.id)
              uploadAvatar(formData).then(response => {
                if (response.code === 200) {
                  this.form.logoInfo = response.msg
                  this.msgSuccess(this.$t('修改成功'))
                } else {
                  this.msgError(response.msg)
                }
              })
            },
            // 校验菜单标识是否重复
            checkMenuKey(rule, value, callback) {
              if (value === null || value === undefined || value === '') {
                return
              }
              const data = {
                id: this.form.id,
                menu: this.form.menu
              }
              checkMenuKey(data).then(response => {
                if (response.data.flag) {
                  callback()
                } else {
                  callback(new Error(response.data.message))
                }
              })
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.open = false
            },
            // 表单重置
            reset() {
              this.form = {
                id: undefined,
                procDefKey: undefined,
                whetherReleaseWorkbench: 'N',
                functionType: undefined,
                sort: undefined,
                logoInfo: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                menu: {
                  id: undefined
                }
              }
              this.resetForm('form')
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                      this.loading = true
                      this.form.procDefName = undefined
                      if (this.form.procDefKeyList) {
                        this.form.procDefKeyList.forEach(key => {
                          this.procDefKeyOptions.forEach(procDef => {
                            if (procDef.key === key) {
                              if (this.form.procDefName) {
                                this.form.procDefName = this.form.procDefName + ',' + procDef.name
                              } else {
                                this.form.procDefName = procDef.name
                              }
                            }
                          })
                        })
                      }
                      saveWfMenuProcess(this.form).then(response => {
                        if (response.code === 200) {
                          this.msgSuccess(this.$t('保存成功'))
                          this.$parent.$parent.open = false
                          this.$parent.$parent.getList()
                        } else {
                          this.msgError(response.msg)
                        }
                        this.loading = false
                      }).catch(() => {
                        this.loading = false
                      })
                    } else {
                      this.locationError(document)
                    }
              })
           },
          /** 查询菜单下拉树结构 */
          getTreeselect() {
            treeselect().then(response => {
              this.menuOptions = []
              const menu = {
                id: 0,
                label: this.$t('主类目'),
                children: []
              }
              menu.children = response.data
              this.menuOptions.push(menu)
            })
          },
          // 根据表单类型获取表单
          getFormList: function(formType, defaultValue) {
            getFormList(formType).then(response => {
              if (response.code === 200) {
                this.formList = response.data
                if (defaultValue !== undefined) {
                  this.form.formId = defaultValue
                }
              } else {
                this.msgError(response.msg)
              }
            })
          },
          // 根据流程定义的Key获取绑定表单的信息
          getFormInfo: function(procDefKey) {
            if (this.isForm) {
              getFormInfo(procDefKey).then(response => {
                if (response.code === 200) {
                  this.form.formType = response.data.formType
                  this.getFormList(response.data.formType, response.data.formId)
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }

        }
    }
</script>
